import { _decorator, Component, Node, BoxCollider2D, Contact2DType, instantiate, IPhysics2DContact, PhysicsSystem2D, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('bullet_control')
export class bullet_control extends Component {
    @property
    speed:number = 500;

    count = 0;//销毁的记录

    start() {

        PhysicsSystem2D.instance.enable = true;

        let collider = this.getComponent(BoxCollider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            // collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
            // collider.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
            // collider.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
        }

    }

    update(deltaTime: number) {

        let p = this.node.getPosition();
            p.y += this.speed*deltaTime;
            if(p.y > 860){
                this.node.destroy();
            }
            this.node.setPosition(p);

    }

    onBeginContact (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        // console.log(otherCollider.tag);
        if(otherCollider.tag == 2){
                if(this.count == 0){
                this.count += 1;
                setTimeout(() => {//此帧处理物理不能销毁，留到下一帧处理。
                // console.log(10)
                this.die()

            },0)
            }
        }
        
        
    }

    die(){
        this.node.destroy();

    }

}


